use std::{collections::HashMap, thread::sleep, time::Duration};

use container_core::workflow::{SimpleWorkflowEngine, SomeChains};
use model_graph_types::{
    assistant::prompts::{PromptTemplateItemBuilder, SYSTEM_ROLE_KEY, USER_ROLE_KEY},
    container::workflow::{
        LlmStatementBuilder, WorkflowBlockBody, WorkflowBlockStatement, WorkflowEngine,
        WorkflowEngineRunOptions, WorkflowModelBuilder,
    },
    database::{ConnectorProtocol, DataSource as DatabaseDataSource, DatabaseType},
    modeling::{set_system_meta_database, Value},
};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();
    tracing::info!("RRAI 启动...");

    set_system_meta_database(DatabaseDataSource {
        id: 0,
        database_type: DatabaseType::SQLite,
        protocol: ConnectorProtocol::SQLite,
        url: String::from("sqlite:/Users/jinisu/rrg01/rrg01.sqlite"),
        ..Default::default()
    })?;

    let body = WorkflowBlockBody::Statement(WorkflowBlockStatement::LLM(
        LlmStatementBuilder::default()
            .model(
                WorkflowModelBuilder::default()
                    .provider("ollama")
                    .name("deepseek-r1:14b")
                    .mode("llm")
                    .build()?,
            )
            .prompt_template(vec![
                PromptTemplateItemBuilder::default()
                    .role(SYSTEM_ROLE_KEY)
                    .text("你是一名专业的程序员！")
                    .build()?,
                PromptTemplateItemBuilder::default()
                    .role(USER_ROLE_KEY)
                    .text("请问冒泡排序是什么？")
                    .build()?,
            ])
            .build()?,
    ));

    let chain = SomeChains::default().get_single_block_chain(body, vec![String::from("text")])?;

    let mut args = HashMap::new();

    args.insert(
        String::from("test"),
        Value::String(String::from("从长篇报告中提取洞察、识别风险并提炼关键信息")),
    );

    let engine = SimpleWorkflowEngine::default();

    let mid = engine
        .run(chain, args, WorkflowEngineRunOptions::default())
        .await?;

    let res = engine.result_with_timeout(&mid, true, 10000000).await;

    match res {
        Ok(response) => {
            tracing::debug!("1{:?}", response);
        }
        Err(err) => {
            tracing::error!("2{:?}", err);
        }
    }
    tokio::select! {
        _ = tokio::signal::ctrl_c() => {
            println!();
        }
    };
    tracing::info!("RRAI 结束...");
    Ok(())
}
